package com.tbit.uqbike.client.service.impl;

import cn.hutool.core.date.DateUtil;
import com.tbit.common.constant.OperationPlatform;
import com.tbit.common.entity.UserOpLog;
import com.tbit.uqbike.client.business.user_op_log.service.UserOpLogService;
import com.tbit.uqbike.client.constant.CardTypeConstant;
import com.tbit.uqbike.client.constant.MemberCardConstant;
import com.tbit.uqbike.client.dao.core.RideCardUserDao;
import com.tbit.uqbike.client.pojo.RideCard;
import com.tbit.uqbike.client.pojo.RideCardUser;
import com.tbit.uqbike.client.pojo.User;
import com.tbit.uqbike.client.service.CardAccountBoundService;
import com.tbit.uqbike.client.service.RideCardService;
import com.tbit.uqbike.client.service.RideCardUserService;
import com.tbit.uqbike.client.service.UserService;
import com.tbit.uqbike.client.util.DateTimeUtil;
import com.tbit.uqbike.client.util.LogUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;

/**
 * 骑行会员用户绑定
 *
 * @author Leon
 * 2019年9月24日 下午4:05:36
 */
@Service("rideCardUserService")
public class RideCardUserServiceImpl implements RideCardUserService {
    @Autowired
    private RideCardUserDao rideCardUserDao;

    @Autowired
    private RideCardService rideCardService;
    @Autowired
    private CardAccountBoundService cardAccountBoundService;
    @Autowired
    private UserOpLogService userOpLogService;
    @Autowired
    private UserService userService;

    @Override
    public List<RideCardUser> queryPage(Integer userId, Integer accountId, Integer pageNO, Integer rowCount) {
        Map<String, Object> map = new HashMap<>();
        map.put("userId", userId);
        map.put("accountId", accountId);
        map.put("start", (pageNO - 1) * rowCount);
        map.put("rowCount", rowCount);

        return rideCardUserDao.queryPage(map);
    }

    @Override
    public Integer queryCount(Integer userId, Integer accountId) {
        Map<String, Object> map = new HashMap<>();
        map.put("userId", userId);
        map.put("accountId", accountId);
        return rideCardUserDao.queryCount(map);
    }

    @Override
    public void insert(RideCardUser rideCardUser) {
        rideCardUser.setBuyTime(DateTimeUtil.getNowTime());

        rideCardUserDao.insert(rideCardUser);
    }

    @Override
    public void updatePay(String orderNO, String daeTime) {
        RideCardUser rideCardUser = new RideCardUser();
        rideCardUser.setOrderNO(orderNO);
        rideCardUser.setBuyTime(daeTime);
        rideCardUserDao.updatePay(rideCardUser);
    }

    @Override
    public RideCardUser getByOrderNO(String orderNO) {
        return rideCardUserDao.getByOrderNO(orderNO);
    }

    @Override
    public void updateUseCount(String orderNO) {
        rideCardUserDao.updateUseCount(orderNO);

        // 插入用户操作日志
        RideCardUser rcu = rideCardUserDao.getByOrderNO(orderNO);
        User user = userService.getByUserId(rcu.getUserId());
        userOpLogService.insertSingle(UserOpLog.builder()
                .accountId(user.getAccountId())
                .opUser(user.getName())
                .opUserPhone(user.getPhone())
                .targetUser(user.getName())
                .targetUserPhone(user.getPhone())
                .operation("骑行卡套餐变动")
                .opType("用户使用")
                .opPlatform(OperationPlatform.CLIENT.code)
                .opTime(LocalDateTime.now())
                .result(true)
                .detail("骑行卡ID: " + rcu.getRideCardId())
                .build());
    }

    @Override
    public void updateValid(String orderNO) {
        rideCardUserDao.updateValid(orderNO);
    }

    @Override
    public void delNotPay(Integer userId) {
        rideCardUserDao.delNotPay(userId);
    }

    @Override
    public List<RideCardUser> getByValid(Integer userId) {
        return rideCardUserDao.getByValid(userId);
    }

    @Override
    public List<RideCardUser> getRideVaildCard(User user, Integer accountId, Integer feeId) {
        /* 查询用户可用骑行卡券 */
        List<RideCardUser> rideCardUsers = checkValid(user.getUserId());
        /*区域骑行卡*/
        List<RideCardUser> list = new ArrayList<>();
        if (rideCardUsers.size() > 0) {
            /*兼容骑行卡区域*/
            for (RideCardUser ride : rideCardUsers) {
                /*每天限制使用次数*/
                if (ride.getUserType().equals(MemberCardConstant.RIDE_CARD_USERTYPE_REDUCE) && ride.getCurrentNum() >= ride.getMaxRide()) {
                    continue;
                }
                RideCard rideCard = rideCardService.getById(ride.getRideCardId());
                /*查询是否存在区域骑行卡互通*/
                List<Integer> accountIds = cardAccountBoundService.getAccountId(accountId, user.getAccountId(), CardTypeConstant.TYPE_RIDECARD);
                //rideCard.getAccountId().equals(accountId)
                if (accountIds.contains(rideCard.getAccountId()) && accountIds.contains(accountId) && ((feeId != null && ride.getFeeId().equals(feeId)) || ride
                        .getFeeId().equals(MemberCardConstant.MACHINE_FEE_ALL))) {
                    if (rideCard.getAccountId().equals(accountId)) {
                        list.add(0, ride);
                    } else {
                        /*feeid大于0，认为是专车型*/
                        if (ride.getFeeId() > MemberCardConstant.MACHINE_FEE_ALL) {
                            list.add(0, ride);
                        } else {
                            list.add(ride);
                        }
                    }
                }
            }
        }

        return list;
    }

    /**
     * 校验是否生效
     *
     * @param userId
     * @return
     */
    @Override
    public List<RideCardUser> checkValid(Integer userId) {
        List<RideCardUser> rideCardUsers = getByValid(userId);
        for (RideCardUser rcu : rideCardUsers) {
            RideCard rideCard = rideCardService.getById(rcu.getRideCardId());

            /* 次数用完置为无效 使用类型 0总共可用、1每日可用*/
            if (rideCard.getMaxRide() != 0 && rcu.getUseCount() >= rideCard.getMaxRide() && Objects
                    .equals(rcu.getUserType(), MemberCardConstant.RIDE_CARD_USERTYPE_TIME)) {
                updateValid(rcu.getOrderNO());
            }
            /* 到期置为无效 */
            if (DateTimeUtil.isBeforeToday(rcu.getEndDate())) {
                LogUtil
                        .info("到期自动置为失效,编号=" + rcu.getOrderNO() + "已使用次数=" + rcu.getUseCount() + "，修改时间=" + DateTimeUtil
                                .getNowTime() + ",失效时间=" + rcu.getEndDate());
                updateValid(rcu.getOrderNO());
            }
            /*更新当前使用次数*/
            if (rcu.getUpdateTime() == null || rcu.getUpdateTime().getTime() < DateUtil.beginOfDay(new Date()).getTime()) {
                rideCardUserDao.updateCurrentNum(rcu.getOrderNO());
            }
        }
        rideCardUsers = getByValid(userId);
        return rideCardUsers;
    }


    @Override
    public List<RideCardUser> getByUserId(Integer userId, Integer accountId) {
        Map<String, Object> map = new HashMap<>();
        map.put("userId", userId);
        map.put("accountId", accountId);
        return rideCardUserDao.getByUserId(map);
    }

    @Override
    public RideCardUser queryByTime(Integer userId) {
        return rideCardUserDao.queryByTime(userId);
    }

    @Override
    public List<RideCardUser> getUserRide(Integer accountId, String startTime, String endTime) {
        Map<String, Object> map = new HashMap<>();
        map.put("startTime", startTime);
        map.put("endTime", endTime);
        map.put("accountId", accountId);
        return rideCardUserDao.getUserRide(map);
    }


    @Override
    public Boolean hasValidRideCard(Integer userId) {
        return rideCardUserDao.countValidRideCard(userId) > 0;
    }

    @Override
    public RideCardUser getRideCardByUserId(Integer accountId, Integer userId) {
        return rideCardUserDao.getRideCardByUserId(accountId, userId);
    }
}
